import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.LocalStorage

Window {
    id: window
    property bool acceptClose: false
    width: 1150
    height: 720
    visible: true
    title: "HJ对战平台"
    Component.onCompleted: {
        window.showMaximized()
        status_bar_label.text = "Init steam."
        if (!SteamAPIBackend.Init()) {
            errorDialog.open();
            return;
        }
        steambackendcallbacktimer.start()
        status_bar_label.text = "Fetching User name."
        username_label.text = SteamAPIBackend.GetPersonalName();
        status_bar_label.text = "Fetching User Avatar."
        user_avatar_image.source = SteamAPIBackend.GetPersonalAvatar()
        status_bar_label.text = "Getting Game Token."
        //var db = LocalStorage.openDatabaseSync("dota683lobby", "1.0", "Store settings and whether has been tested", 1000000)
        //db.transaction(function(tx) {
        //    tx.executeSql('CREATE TABLE IF NOT EXISTS config(k text, v text)')
        //    var rs = tx.executeSql('SELECT v FROM config where k = "launch_game_tested" LIMIT 1')
        //    console.log("rs row " + rs.rows.length)
        //    if (rs.rows.length > 0) {
        //        test_launch_instruction.visible = false
        //        match_button_layout.visible = true
        //        SteamAPIBackend.SetTestLaunchComplete()
        //    } else {
        //        console.log("first time launch app, block showing test button.")
        //    }
        //})
        if (!SteamAPIBackend.ConnectToGameServer()) {
            errorDialog.title = "连接服务器失败"
            errorDialog.open();
            return;
        }
    }

    onClosing: (close) => {
        console.log("Handle closing event");
        if (!window.acceptClose) {
            SteamAPIBackend.LeaveLobby()
            SteamAPIBackend.CancelMatchMaking()
            window.acceptClose = true
            close.accepted = false
            close_window_timer.start()
        }
    }

    Timer {
        id: steambackendcallbacktimer
        interval: 100;
        running: false;
        repeat: true;
        onTriggered: SteamAPIBackend.RunCallbacks()
    }

    Timer {
        id: close_window_timer
        interval: 1000;
        running: false;
        repeat: false;
        onTriggered: window.close()
    }

    Timer {
        id: waittimetimer
        interval: 1000;
        running: false;
        repeat: true;
        onTriggered: wait_time_label.wait_time += 1
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 2
        Rectangle {
            Layout.alignment: Qt.AlignCenter
            Layout.fillHeight: true
            Layout.fillWidth: true
            color: "#F8FFF2"
            RowLayout {
                anchors.fill: parent
                spacing: 2
                Rectangle {
                    Layout.alignment: Qt.AlignCenter
                    color: "#F8FFF2"
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    //ColumnLayout {
                    //    id: test_launch_instruction
                    //    anchors.centerIn:parent
                    //    spacing: 5
                    //    Label {
                    //        id: test_instruction_label
                    //        text: "欢迎来到怀旧对战平台，这里可以玩Dota 683版本的排位比赛。\n这是你第一次访问，我们需要测试你是否有安装有效的游戏文件。\n你需要安装Dota 2游廊地图《Dota6.83怀旧服》，设置Dota2游戏分辨率为1920*1080，并把Dota 2的语言设置成中文，\n因为我们会在找到游戏匹配后用图像匹配，控制鼠标的方式进入游戏。\n准备好后，请点击下方的按钮测试启动游戏，我们会尝试创建《Dota6.83怀旧服》地图rank模式的房间。"
                    //    }

                    //    Label {
                    //        id: init_failed_label
                    //        objectName: "init_failed_label"
                    //        color: "red"
                    //        text: "启动失败"
                    //        visible: false
                    //    }

                    //    Button {
                    //        id: test_launch_button
                    //        objectName: "test_launch_button"
                    //        Layout.preferredWidth: 150
                    //        Layout.preferredHeight: 50
                    //        anchors.horizontalCenter: parent.horizontalCenter
                    //        text: test_launch_button.enabled ? "测试启动游戏" :  "测试中"
                    //        onClicked: {
                    //            test_launch_button.enabled = false
                    //            SteamAPIBackend.TestLaunchGame()
                    //        }
                    //    }
                    //}

                    ColumnLayout {
                        id: match_button_layout
                        objectName: "match_button_layout"
                        anchors.centerIn:parent
                        spacing: 10
                        property var mode: "no_queue" // no_queue, queue, start
                        ListView {
                            objectName: "lobby_list_view"
                            orientation: Qt.Horizontal
                            model: lobbyModel
                            implicitHeight: 140
                            implicitWidth: lobbyModel.length * 70
                            anchors.horizontalCenter: parent.horizontalCenter
                            spacing: 5
                            delegate: ColumnLayout {
                                required property string name
                                required property string sid
                                required property bool isHost
                                required property bool isSelf
                                required property bool selfIsHost
                                required property int state
                                width: 64
                                Component.onCompleted: {
                                    console.log("Created lobby player " + name + " " + state)
                                }
                                Image {
                                    source: "image://lobby/" + parent.sid;
                                }
                                Label {
                                    text: parent.name
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }
                                RowLayout{
                                    anchors.horizontalCenter: parent.horizontalCenter
                                    Image {
                                        visible: parent.parent.isHost
                                        source: "/pics/house-door-fill.svg"
                                        Layout.preferredHeight: 20
                                        Layout.preferredWidth: 20
                                    }
                                    Image {
                                        visible: parent.parent.state == 1
                                        source: "/pics/check.svg"
                                        Layout.preferredHeight: 20
                                        Layout.preferredWidth: 20
                                    }
                                }
                                RoundButton {
                                    anchors.horizontalCenter: parent.horizontalCenter
                                    icon.source: parent.isSelf ? "/pics/door-open-fill.svg" : "/pics/x-lg.svg"
                                    height: 25
                                    width: 25
                                    visible: parent.isSelf || parent.selfIsHost
                                    onClicked: {
                                        if (parent.isSelf) {
                                            SteamAPIBackend.LeaveLobby()
                                        } else {
                                            SteamAPIBackend.LobbyKickPlayer(parent.sid)
                                        }
                                    }
                                }
                            }
                        }

                        //RowLayout {
                        //    spacing: 10
                        //    anchors.horizontalCenter: parent.horizontalCenter
                        //    Label {
                        //        objectName: "player_score_label"
                        //        text: "分：1000"
                        //    }
                        //    RoundButton {
                        //        icon.source: "/pics/arrow-clockwise.svg"
                        //        Layout.preferredWidth: 25
                        //        Layout.preferredHeight: 25
                        //        onClicked: SteamAPIBackend.RefreshPlayerScore()
                        //    }
                        //}

                        Label {
                            id: wait_time_label
                            objectName: "wait_time_label"
                            visible: false
                            property var wait_time: 0
                            text: "等待时间：" + wait_time
                            anchors.horizontalCenter: parent.horizontalCenter
                        }

                        Button {
                            id: start_match_button
                            objectName: "start_match_button"
                            Layout.preferredWidth: 150
                            Layout.preferredHeight: 50
                            anchors.horizontalCenter: parent.horizontalCenter
                            text: match_button_layout.mode == "no_queue" ? "开始匹配": (match_button_layout.mode == "queue" ? "取消匹配":"放弃游戏")
                            onClicked: {
                                console.log(match_button_layout.mode)
                                if (match_button_layout.mode == "no_queue") {
                                    waittimetimer.start()
                                    wait_time_label.visible = true
                                    SteamAPIBackend.StartMatchMaking()
                                    match_button_layout.mode = "queue"
                                } else if (match_button_layout.mode == "queue") {
                                    waittimetimer.stop()
                                    wait_time_label.visible = false
                                    SteamAPIBackend.CancelMatchMaking()
                                    match_button_layout.mode = "no_queue"
                                } else {
                                    wait_time_label.visible = false
                                    SteamAPIBackend.CancelLaunchOrGame()
                                    match_button_layout.mode = "no_queue"
                                }
                            }
                        }

                        Button {
                            id: ready_button
                            property bool is_ready: false
                            objectName: "ready_button"
                            Layout.preferredWidth: 150
                            Layout.preferredHeight: 50
                            text: ready_button.is_ready ? "取消准备" : "准备"
                            visible: false
                            onClicked: {
                                ready_button.is_ready = !ready_button.is_ready
                                SteamAPIBackend.SetLobbyReady(ready_button.is_ready)
                            }
                        }
                    }

                    ColumnLayout {
                        id: game_join_state_column
                        anchors.right: parent.right
                        anchors.top: parent.top
                        anchors.topMargin: 10
                        anchors.rightMargin: 10

                        RowLayout {
                            spacing: 5
                            anchors.horizontalCenter: parent.horizontalCenter
                            Label {
                                objectName: "queue_count_label"
                                text: "排位人数：0"
                            }
                            RoundButton {
                                icon.source: "/pics/arrow-clockwise.svg"
                                Layout.preferredWidth: 25
                                Layout.preferredHeight: 25
                                onClicked: SteamAPIBackend.RefreshQueueCount()
                            }
                        }

                        RowLayout {
                            spacing: 10
                            Label {
                                id: game_join_state_label_title
                                text: "游戏房间："
                            }
                            RoundButton {
                                Layout.preferredWidth: 25
                                Layout.preferredHeight: 25
                                icon.source: "/pics/arrow-clockwise.svg"
                                onClicked: SteamAPIBackend.RefreshGameJoinState()
                            }
                        }

                        Label {
                            id: game_join_state_label_content
                            objectName: "game_join_state_label_content"
                            text: "未创建"
                        }
                    }
                    RowLayout {
                        height: 30
                        anchors.left: parent.left
                        anchors.leftMargin: 5
                        anchors.bottom: player_summary_row.top
                        spacing: 10
                        Rectangle {
                            anchors.fill: parent
                            anchors.rightMargin: -20
                            anchors.leftMargin: -20
                            color: "#68830F"
                        }
                        Label {
                            text: "战绩"
                            font.pixelSize: 20
                            font.bold: true
                            color: "white"
                        }
                        RoundButton {
                            Layout.preferredHeight: 25
                            Layout.preferredWidth: 25
                            icon.source: "/pics/arrow-clockwise.svg"
                            onClicked: {
                                SteamAPIBackend.RefreshPlayerScore()
                                SteamAPIBackend.RefreshGameHistory()
                            }
                        }
                    }

                    RowLayout {
                        id: player_summary_row
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.bottom: gameHistoryView.top
                        height: 40
                        spacing: 15
                        Rectangle {
                            anchors.fill: parent
                            anchors.rightMargin: -20
                            anchors.leftMargin: -20
                            color: "#CFFB9C"
                        }

                        ColumnLayout {
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                text: "天梯6.83"
                            }
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                objectName: "player_score_label"
                                text: "1000"
                            }
                        }
                        ToolSeparator { }
                        ColumnLayout {
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                text: "总场次"
                            }
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                objectName: "total_games_label"
                                text: "0"
                            }
                        }
                        ToolSeparator { }
                        ColumnLayout {
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                text: "胜率"
                            }
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                objectName: "win_percent_label"
                                text: "50%"
                            }
                        }
                        ToolSeparator { }
                        ColumnLayout {
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                text: "胜利场次"
                            }
                            Label {
                                anchors.horizontalCenter: parent.horizontalCenter
                                objectName: "win_total_label"
                                text: "0"
                            }
                        }
                    }

                    ListView {
                        id: gameHistoryView
                        width: 300
                        anchors.bottom: parent.bottom
                        anchors.left: parent.left
                        anchors.leftMargin: 15
                        height: 320
                        model: gameHistoryModel
                        property list<string> hero2icon:["0",
                            "Anti-Mage","Axe","Bane","Bloodseeker","Crystal_Maiden","Drow_Ranger","Earthshaker","Juggernaut","Mirana","Shadow_Fiend",
                            "Morphling","Phantom_Lancer","Puck","Pudge","Razor","Sand_King","Storm_Spirit","Sven","Tiny","Vengeful_Spirit",
                            "Windranger","Zeus","Kunkka","24","Lina","Lion","Shadow_Shaman","Slardar","Tidehunter","Witch_Docker",
                            "Lich","Riki","Enigma","Tinker","Sniper","Necrophos","Warlock","Beastmaster","Queen_of_Pain","Venomancer",
                            "Faceless_Void","Wraith_King","Death_Prophet","Phantom_Assassin","Pugna","Templar_Assassin","Viper","Luna","Dragon_Knight","Dazzle",
                            "Clockwerk","Leshrac","Nature's_Prophet","Lifestealer","Dark_Seer","Clinkz","Omniknight","Enchantress","Huskar","Night_Stalker",
                            "Broodmother","Bounty_Hunter","Weaver","Jakiro","Batrider","Chen","Spectre","Ancient_Apparition","Doom","Ursa",
                            "Spirit_Breaker","Gyrocopter","Alchemist","Invoker","Silencer","Outworld_Destroyer","Lycan","Brewmaster","Shadow_Demon","Lone_Druid",
                            "Chaos_Knight","Meepo","Treant_Protector","Ogre_Magi","Undying","Rubick","Disruptor","Nyx_Assassin","Naga_Siren","Keeper_of_the_Light",
                            "Io","Visage","Slark","Medusa","Troll_Warlord","Centaur_Warrunner","Magnus","Timbersaw","Bristleback","Tusk",
                            "Skywrath_Mage","Abaddon","Elder_Titan","Legion_Commander","Techies","Ember_Spirit","Earth_Spirit","Underlord","Terrorblade","Pheonix",
                            "Oracle","Winter_Wyvern","Arc_Warden","Phantom_Lancer","115","116","117","118","Puck","Juggernaut",
                            "Lich","122","Windranger","124","125","Ember_Spirit","127","Mirana","Dragon_Knight","130",
                            "Rubick","132","133","134","Omniknight","Anti-Mage","Slardar","Medusa","139","140",
                            "141","142","143","144","Sven"]
                        delegate: RowLayout {
                            required property string date
                            required property string rslt
                            required property string kda
                            required property int hrid
                            height: 32
                            spacing: 25
                            Rectangle {
                                anchors.fill: parent
                                color: "#E2FFC8"
                                anchors.leftMargin: -30
                                anchors.rightMargin: -15
                                MenuSeparator {
                                    anchors.bottom: parent.bottom
                                    width: parent.width
                                }
                            }

                            Image {
                                source: "/pics/" + gameHistoryView.hero2icon[parent.hrid] + "_minimap_icon.png"
                                Layout.preferredHeight: 32
                                Layout.preferredWidth: 32
                            }

                            Label {
                                text: parent.rslt == 0 ? "胜利":"失败"
                                color: parent.rslt == 0 ? "green":"red"
                            }

                            Label {
                                text: parent.date
                            }

                            Label {
                                text: parent.kda
                            }
                        }
                    }
                }

                Rectangle {
                    Layout.alignment: Qt.AlignRight
                    color: "#ECFFC8"
                    Layout.preferredWidth: 200
                    Layout.fillHeight: true
                    Rectangle {
                        Layout.preferredHeight: 40
                        Layout.fillWidth: true
                        anchors.top: parent.top
                        color: "#CFFB9C"
                        RowLayout {
                            anchors.fill: parent
                            Image {
                                id: user_avatar_image
                                Layout.preferredHeight: 32
                                Layout.preferredWidth: 32
                                source: "/pics/account-logo-png-11.png"
                                Layout.leftMargin: 2
                            }
                            Label {
                                id: username_label
                                Layout.alignment: Qt.AlignLeft
                                text: "0-15"
                            }
                        }
                    }

                    Label {
                        anchors {
                            top: parent.top
                            topMargin: 40
                            left: parent.left
                            leftMargin: 5
                        }
                        text: "好友："
                    }

                    Rectangle {
                        anchors {
                            top: parent.top
                            topMargin: 60
                        }
                        width: parent.width
                        height: 25
                        RoundButton {
                            anchors.left: parent.left
                            height: 25
                            width: 25
                            icon.source: "/pics/arrow-clockwise.svg"
                            onClicked: {
                                friendsModel.reset()
                            }
                        }
                        TextInput {
                            id: friendFilterInput
                            anchors {
                                left: parent.left
                                right: parent.right
                                verticalCenter: parent.verticalCenter
                                leftMargin: 30
                                rightMargin: 60
                            }
                        }
                        RoundButton {
                            anchors.right: parent.right
                            anchors.rightMargin: 25
                            height: 25
                            width: 25
                            icon.source: "/pics/search.svg"
                            enabled: friendFilterInput.text.length > 0
                            onClicked: {
                                friendsModel.FilterByName(friendFilterInput.text);
                            }
                        }
                        RoundButton {
                            anchors.right: parent.right
                            height: 25
                            width: 25
                            icon.source: "/pics/x-lg.svg"
                            onClicked: {
                                friendFilterInput.clear();
                                friendsModel.ClearFilter();
                            }
                        }
                    }

                    ListView {
                        id: friendsView
                        Layout.fillWidth: true
                        anchors.fill: parent
                        anchors.topMargin: 90
                        anchors.leftMargin: 5
                        anchors.bottomMargin: 100
                        model: friendsModel
                        clip: true
                        delegate: Rectangle {
                            id: friendsDelegate
                            required property string name
                            required property int state
                            required property string sid
                            property bool invitation_sent: false
                            height: 25
                            width: 180
                            color: "#00000000"
                            Image {
                                width: 24
                                height: 24
                                anchors {
                                    left: parent.left
                                    verticalCenter: parent.verticalCenter
                                }
                                source: "image://friend/" + parent.sid;
                            }

                            Label {
                                text: parent.name
                                color: parent.state == 1 ? "black":"grey"
                                Layout.maximumWidth: 150
                                anchors {
                                    left: parent.left
                                    leftMargin: 27
                                    verticalCenter: parent.verticalCenter
                                }
                            }

                            Button {
                                icon.source: "/pics/send.svg"
                                icon.color: parent.invitation_sent ? "#87B21F":"black"
                                anchors.right: parent.right
                                anchors.verticalCenter: parent.verticalCenter
                                height: 20
                                onClicked: {
                                    parent.invitation_sent = !parent.invitation_sent
                                    SteamAPIBackend.SendInvitation(parent.invitation_sent, parent.sid)
                                }
                            }
                        }
                    }
                    Rectangle {
                        id: friend_invite_rect
                        border.color: "#87B21F"
                        width: parent.width
                        anchors.bottom: parent.bottom
                        anchors.horizontalCenter: parent.horizontalCenter

                        height: 80
                        visible: false
                        ColumnLayout {
                            anchors.fill: parent
                            RowLayout {
                                anchors.horizontalCenter: parent.horizontalCenter
                                spacing: 10
                                Label {
                                    id: friend_invite_name
                                    text: "0-16"
                                }
                                Label {
                                    text: "邀请你组队"
                                }
                            }
                            RowLayout {
                                anchors.horizontalCenter: parent.horizontalCenter
                                spacing: 10
                                Button {
                                    text: "接受"
                                    onClicked: {
                                        SteamAPIBackend.AcceptInvite(window.friend_invite_sid)
                                        friend_invite_rect.visible = false
                                    }
                                }
                                Button {
                                    text: "拒绝"
                                    onClicked: {
                                        SteamAPIBackend.DeclineInvite(window.friend_invite_sid)
                                        friend_invite_rect.visible = false
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            color: "#87B21F"
            RowLayout {
                anchors.fill: parent
                layoutDirection: Qt.RightToLeft
                spacing: 2
                //RoundButton {
                //    text: "测"
                //    Layout.rightMargin: 2
                //    onClicked: {
                //        SteamAPIBackend.TestLaunchGame()
                //        //window.displayFriendInvite("123456", "654321")
                //    }
                //}
                Label {
                    id: status_bar_label
                    objectName: "status_bar_label"
                    text: "Doing something..."
                }
            }
        }
    }
    Dialog {
        id: errorDialog
        anchors.centerIn: parent
        title: "Steam init failed!!!"
        standardButtons: Dialog.Close
        onRejected: window.close()
        parent: Overlay.overlay
    }
    Dialog {
        id: continueHostDialog
        anchors.centerIn: parent
        standardButtons: Dialog.Cancel
        Button {
            text: "已手动创建房间"
            onClicked: {
                SteamAPIBackend.ManualHostGameSuccess()
                continueHostDialog.accept()
            }
        }
    }
	Audio {
		id: readyMusic
		source: "sounds/tomtom.mp3"
		duration: 2
	}

    function showContinueHostDialog(gid: string): void {
        continueHostDialog.title = "创建房间失败，请手动创建房间，密码：" + gid
        continueHostDialog.open()
    }

    function handleTestLaunchSuccess(): void {
        match_button_layout.visible = true
        test_launch_instruction.visible = false
        console.log("test pass")
        //var db = LocalStorage.openDatabaseSync("dota683lobby", "1.0", "Store settings and whether has been tested", 1000000)
        //db.transaction(function(tx) {
        //    tx.executeSql("INSERT INTO config VALUES(?, ?)", ["launch_game_tested", "true"])
        //})
    }

    function handleMatchGameFound(): void {
        waittimetimer.stop()
        wait_time_label.text = "正在进入游戏"
        match_button_layout.mode = "start"
		window.raise()
		readyMusic.play()
    }

    function handleLaunchFailure(): void {
        //console.log("Clearing launch_game_tested flag in db.")
        //var db = LocalStorage.openDatabaseSync("dota683lobby", "1.0", "Store settings and whether has been tested", 1000000)
        //db.transaction(function(tx) {
        //    tx.executeSql("DELETE FROM config WHERE k = ?", ["launch_game_tested"])
        //})
        test_launch_instruction.visible = true
        match_button_layout.visible = false
        init_failed_label.visible = true
        init_failed_label.text = "启动游戏失败，请调整配置后重新测试"
    }

    property string friend_invite_sid;
    function displayFriendInvite(name, fsid): void {
        console.log("displayFriendInvite " + fsid)
        friend_invite_sid = fsid
        friend_invite_name.text = name
        friend_invite_rect.visible = true
    }

    function stopQueueFrontendOnly() {
        waittimetimer.stop()
        wait_time_label.visible = false
        match_button_layout.mode = "no_queue"
    }
}
